package com.haifeng.lyw.blerobot;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.haifeng.lyw.blerobot.custom.DragViewCtr;
import com.haifeng.lyw.blerobot.dialog.ChassisDialog;
import com.haifeng.lyw.blerobot.service.BluetoothLeService;
import com.haifeng.lyw.blerobot.utils.BleInfo;
import com.haifeng.lyw.blerobot.utils.FbController;
import com.haifeng.lyw.blerobot.utils.L;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ActionActivity extends Activity implements View.OnTouchListener , FbController.OnNavAndSpeedListener{

    ImageView mForearmUp, mForearmDown,  mPostUp, mPostDown;
    ImageView mEleOneLeft, mEleOneRight, mEleTwoUp, mEleTwoDown, mPushOneUp, mPushOneDown, mPushTwoUp, mPushTwoDown, mTurbineOpen, mTurbineClose;
    private String TAG = "ActionActivity";

    //Cam参数
    private String strAccount;
    private String strPwd;
    private boolean isSelect;
    private  OrientationEventListener mOrientationListener;
    //自定义悬浮按钮
//    private DragViewCtr ctr = null;
    //加载dialog
    private ProgressDialog progressDialog;

    //蓝牙连接状态
    private boolean mConnected = false;
    private String status = "disconnected";
    //蓝牙名字
    private String mDeviceName;
    //蓝牙地址
    private String mDeviceAddress;
    //蓝牙信号值
    private String mRssi;
    private Bundle b;
    private String rev_str = "";
    String code = "";
    private int mNav;
    //蓝牙service,负责后台的蓝牙服务
    private static BluetoothLeService mBluetoothLeService;

//    private ImageView mConnectingImg, mConnectedImg, mNoConnectImg;
private TextView tv_con;
    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<>();
    //蓝牙特征值
    private static BluetoothGattCharacteristic target_chara = null;
    private boolean isTouch;
    private Handler mhandler = new Handler();
    private Handler myHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (progressDialog != null && progressDialog.isShowing())
                        progressDialog.dismiss();
                    if (mConnected) {
                        //连接成功
                        setEnabled(true);

                    } else {
                        //连接失败
                        setEnabled(false);
                    }
                    String state = msg.getData().getString("connect_state");
                    break;
                case 2:
                    if (isTouch) {

                        if (!TextUtils.isEmpty(code))
                            sendByBle(code);
                        myHandler.sendEmptyMessageDelayed(2, 650);
                    }

                    break;
                case 3:
                    L.i(TAG, "抬起 code-->" + code);
                    if (!TextUtils.isEmpty(code))
                        sendByBle(code);
                    myHandler.sendEmptyMessage(2);
                    code = "";
                    myHandler.removeMessages(2);
                    isTouch = false;
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        fullScreen();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b = getIntent().getExtras();
        //从意图获取显示的蓝牙信息
        mDeviceName = b.getString(BleInfo.EXTRAS_DEVICE_NAME);
        mDeviceAddress = b.getString(BleInfo.EXTRAS_DEVICE_ADDRESS);
        mRssi = b.getString(BleInfo.EXTRAS_DEVICE_RSSI);

        FbController navController= (FbController) findViewById(R.id.fb_control);
        navController.setOnNavAndSpeedListener(this);

		/* 启动蓝牙service */
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);

        initView();

    }

    // Activity出来时候，绑定广播接收器，监听蓝牙连接服务传过来的事件
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onResume() {
        super.onResume();
       /* if (ctr == null) {
            ctr = new DragViewCtr(this);
            ctr.showDragCallView();
            ctr.setOnClickListener(dragClickListener);
        }*/

        if (!mConnected) {
            //显示ProgressDialog
            progressDialog = ProgressDialog.show(this, "", "正在尝试连接蓝牙", true, false);
            //绑定广播接收器
            registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
            if (mBluetoothLeService != null) {
                //根据蓝牙地址，建立连接
                final boolean result = mBluetoothLeService.connect(mDeviceAddress);
                Log.d(TAG, "Connect request result=" + result);
                if (!result)
                    if (progressDialog != null && progressDialog.isShowing())
                        progressDialog.dismiss();
            }
        }
    }

    private ChassisDialog mChassisDialog = null;

    DragViewCtr.OnClickListener dragClickListener = new DragViewCtr.OnClickListener() {
        @Override
        public void onClick() {
            /*if (ctr != null)
                ctr.setCanDrag(false);*/
            //显示自定义Dialog
            if (mChassisDialog == null) {
                mChassisDialog = new ChassisDialog(ActionActivity.this, "底盘、前后臂运动控制", -1);
            }
            if (!mChassisDialog.isShowing()) {
                mChassisDialog.show();
                mChassisDialog.setClicklistener(new ChassisDialog.ClickListenerInterface() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
                    @Override
                    public void send(int id, boolean action) {
                        if (!action) {
                            myHandler.removeMessages(2);
                        }
                        sendOrder(id, action);
                    }

                    @Override
                    public void dissmis() {
                       /* if (ctr != null)
                            ctr.setCanDrag(true);*/
                        fullScreen();
                    }
                });
            }
        }
    };



    /**
     * 初始化数据
     */
    private void initView() {
        mForearmUp = (ImageView) findViewById(R.id.forearm_up);
        mForearmUp.setOnTouchListener(this);
        mForearmDown = (ImageView) findViewById(R.id.forearm_down);

        mForearmDown.setOnTouchListener(this);
        tv_con=findViewById(R.id.tv_con);


//        mCam=(ImageView) findViewById(R.id.main_cam);
//        mCam.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
////                Log.i("WWDZ","111");
//
//               setButtonVieible();
//
//
//            }
//        });
//        mchassisfront = (ImageView) findViewById(R.id.chassis_front);
//        mchassisfront.setOnTouchListener(this);
//        mchassisBack = (ImageView) findViewById(R.id.chassis_back);
//        mchassisBack.setOnTouchListener(this);
//        mchassisLeft = (ImageView) findViewById(R.id.chassis_left);
//        mchassisLeft.setOnTouchListener(this);
//        mchassisRight = (ImageView) findViewById(R.id.chassis_right);
//        mchassisRight.setOnTouchListener(this);
        mPostUp = (ImageView) findViewById(R.id.postbrachium_up);
        mPostUp.setOnTouchListener(this);
        mPostDown = (ImageView) findViewById(R.id.postbrachium_down);
        mPostDown.setOnTouchListener(this);
//        mEleOneLeft = (ImageView) findViewById(R.id.ele_one_left);
//        mEleOneLeft.setOnTouchListener(this);
//        mEleOneRight = (ImageView) findViewById(R.id.ele_one_right);
//        mEleOneRight.setOnTouchListener(this);
//        mEleTwoUp = (ImageView) findViewById(R.id.ele_two_up);
//        mEleTwoUp.setOnTouchListener(this);
//        mEleTwoDown = (ImageView) findViewById(R.id.ele_two_down);
//        mEleTwoDown.setOnTouchListener(this);
//        mPushOneUp = (ImageView) findViewById(R.id.push_one_up);
//        mPushOneUp.setOnTouchListener(this);
//        mPushOneDown = (ImageView) findViewById(R.id.push_one_down);
//        mPushOneDown.setOnTouchListener(this);
//        mPushTwoUp = (ImageView) findViewById(R.id.push_two_up);
//        mPushTwoUp.setOnTouchListener(this);
//        mPushTwoDown = (ImageView) findViewById(R.id.push_two_down);
//        mPushTwoDown.setOnTouchListener(this);
//        mTurbineOpen = (ImageView) findViewById(R.id.turbine_up);
//        mTurbineOpen.setOnTouchListener(this);
//        mTurbineClose = (ImageView) findViewById(R.id.turbine_down);
//        mTurbineClose.setOnTouchListener(this);
//
//        mConnectingImg = (ImageView) findViewById(R.id.connecting);
//        mConnectedImg = (ImageView) findViewById(R.id.connected);
//        mNoConnectImg = (ImageView) findViewById(R.id.no_connect);
//
//        // setEnabled(false);
//
//        mConnectingImg.setBackgroundResource(R.mipmap.connecting_current);





    }



    private void setEnabled(boolean enabled) {
        mForearmUp.setEnabled(enabled);
        mForearmDown.setEnabled(enabled);

        mPostUp.setEnabled(enabled);
        mPostDown.setEnabled(enabled);

        tv_con.setText(enabled ? "已连接" : "正在连接..");
//        mConnectingImg.setBackgroundResource(R.mipmap.connecting_normal);
//        mConnectedImg.setBackgroundResource(enabled ? R.mipmap.connected_current : R.mipmap.connected_normal);
//        mNoConnectImg.setBackgroundResource(!enabled ? R.mipmap.noconnect_current : R.mipmap.noconnect_normal);
    }

    /* BluetoothLeService绑定的回调函数 */
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
                    .getService();
            if (!mBluetoothLeService.initialize()) {
                L.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up
            // initialization.
            // 根据蓝牙地址，连接设备
            mBluetoothLeService.connect(mDeviceAddress);

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }

    };

    /**
     * 广播接收器，负责接收BluetoothLeService类发送的数据
     */
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {//Gatt连接成功
                mConnected = true;
                status = "已连接";
                //更新连接状态
                updateConnectionState(status);
                System.out.println("BroadcastReceiver :" + "device connected");

            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {//Gatt连接失败
                mConnected = false;
                status = "连接失败";

                //更新连接状态
                updateConnectionState(status);
                System.out.println("BroadcastReceiver :"
                        + "device disconnected");

            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {//发现GATT服务器
                // Show all the supported services and characteristics on the
                // user interface.
                //获取设备的所有蓝牙服务
                displayGattServices(mBluetoothLeService.getSupportedGattServices());
                System.out.println("BroadcastReceiver :device SERVICES_DISCOVERED");
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {//有效数据
                //处理发送过来的数据
                displayData(intent.getExtras().getString(BluetoothLeService.EXTRA_DATA));
                System.out.println("BroadcastReceiver onData:"
                        + intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            }
        }
    };

    /* 更新连接状态 */
    private void updateConnectionState(String status) {
        Message msg = new Message();
        msg.what = 1;
        Bundle b = new Bundle();
        b.putString("connect_state", status);
        msg.setData(b);
        //将连接状态更新的UI的textview上
        myHandler.sendMessage(msg);
        System.out.println("connect_state:" + status);

    }

    /* 意图过滤器 */
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter
                .addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    /**
     * @param @param rev_string(接受的数据)
     * @return void
     * @throws
     * @Title: displayData
     * @Description: TODO(接收到的数据在scrollview上显示)
     */
    private void displayData(String rev_string) {
        rev_str += rev_string;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                rev_tv.setText(rev_str);
//                rev_sv.scrollTo(0, rev_tv.getMeasuredHeight());
                System.out.println("rev:" + rev_str);
            }
        });
    }

    /**
     * @param
     * @return void
     * @throws
     * @Title: displayGattServices
     * @Description: TODO(处理蓝牙服务)
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void displayGattServices(List<BluetoothGattService> gattServices) {

        if (gattServices == null)
            return;
        String uuid = null;
        String unknownServiceString = "unknown_service";
        String unknownCharaString = "unknown_characteristic";

        // 服务数据,可扩展下拉列表的第一级数据
        ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();

        // 特征数据（隶属于某一级服务下面的特征值集合）
        ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData = new ArrayList<ArrayList<HashMap<String, String>>>();

        // 部分层次，所有特征值集合
        mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {

            // 获取服务列表
            HashMap<String, String> currentServiceData = new HashMap<String, String>();
            uuid = gattService.getUuid().toString();

            // 查表，根据该uuid获取对应的服务名称。SampleGattAttributes这个表需要自定义。

            gattServiceData.add(currentServiceData);

            System.out.println("Service uuid:" + uuid);

            ArrayList<HashMap<String, String>> gattCharacteristicGroupData = new ArrayList<HashMap<String, String>>();

            // 从当前循环所指向的服务中读取特征值列表
            List<BluetoothGattCharacteristic> gattCharacteristics = gattService
                    .getCharacteristics();

            ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();

            // Loops through available Characteristics.
            // 对于当前循环所指向的服务中的每一个特征值
            for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
                HashMap<String, String> currentCharaData = new HashMap<String, String>();
                uuid = gattCharacteristic.getUuid().toString();

                if (gattCharacteristic.getUuid().toString()
                        .equals(BleInfo.HEART_RATE_MEASUREMENT)) {
                    // 测试读取当前Characteristic数据，会触发mOnDataAvailable.onCharacteristicRead()
                    mhandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            mBluetoothLeService
                                    .readCharacteristic(gattCharacteristic);
                        }
                    }, 200);

                    // 接受Characteristic被写的通知,收到蓝牙模块的数据后会触发mOnDataAvailable.onCharacteristicWrite()
                    mBluetoothLeService.setCharacteristicNotification(
                            gattCharacteristic, true);
                    target_chara = gattCharacteristic;
                    // 设置数据内容
                    // 往蓝牙模块写入数据
                    // mBluetoothLeService.writeCharacteristic(gattCharacteristic);
                }
                List<BluetoothGattDescriptor> descriptors = gattCharacteristic
                        .getDescriptors();
                for (BluetoothGattDescriptor descriptor : descriptors) {
                    System.out.println("---descriptor UUID:"
                            + descriptor.getUuid());
                    // 获取特征值的描述
                    mBluetoothLeService.getCharacteristicDescriptor(descriptor);
                    // mBluetoothLeService.setCharacteristicNotification(gattCharacteristic,
                    // true);
                }

                gattCharacteristicGroupData.add(currentCharaData);
            }
            // 按先后顺序，分层次放入特征值集合中，只有特征值
            mGattCharacteristics.add(charas);
            // 构件第二级扩展列表（服务下面的特征值）
            gattCharacteristicData.add(gattCharacteristicGroupData);

        }

    }


    /**
     * 设置全屏
     */
    public void fullScreen() {
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar

        if (android.os.Build.VERSION.SDK_INT >= 19) {
            uiFlags |= 0x00001000;    //SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide navigation bars - compatibility: building API level is lower thatn 19, use magic number directly for higher API target level
        } else {
            uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }

        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                L.e(TAG, "按钮按下");
                sendOrder(v.getId(), true);
                break;
            case MotionEvent.ACTION_UP:
                L.e(TAG, "按钮抬起");
                sendOrder(v.getId(), false);
                myHandler.removeMessages(2);
                break;
        }
        return false;
    }




    /**
     * 发送指令
     *
     * @param id     按钮
     * @param action true 按下；false 抬起
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void sendOrder(int id, boolean action) {
        if (!isTouch) {
            isTouch = true;
            switch (id) {
                case R.id.forearm_up://前臂向上

                    code = "1";

                    break;
                case R.id.forearm_down://前臂向下

                    code = "7";

                    break;
//                case R.id.postbrachium_up://后臂向上
//
//                    code = "3";
//
//                    break;
//                case R.id.postbrachium_down://后臂向下
//
//                    code = "9";
//
//                    break;
           /* case R.id.chassis_front://地盘向前
                if (action)
                    code = "2";
                else
                    code = "5";
                break;
            case R.id.chassis_back://地盘向后
                if (action)
                    code = "8";
                else
                    code = "5";
                break;
            case R.id.chassis_left://地盘向左
                if (action)
                    code = "4";
                else
                    code = "5";
                break;
            case R.id.chassis_right://地盘向右
                if (action)
                    code = "6";
                else
                    code = "5";
                break;
                case R.id.ele_one_left://电机1 向左
                    if (action)
                        code = "I";
                    else
                        code = "J";
                    break;
                case R.id.ele_one_right://电机1 向右
                    if (action)
                        code = "K";
                    else
                        code = "J";
                    break;
                case R.id.ele_two_up://电机2 向上
                    if (action)
                        code = "L";
                    else
                        code = "M";
                    break;
                case R.id.ele_two_down://电机2 向下
                    if (action)
                        code = "N";
                    else
                        code = "M";
                    break;
                case R.id.push_one_up://推杆1 向上
                    if (action)
                        code = "R";
                    else
                        code = "S";
                    break;
                case R.id.push_one_down://推杆1 向下
                    if (action)
                        code = "T";
                    else
                        code = "S";
                    break;
                case R.id.push_two_up://推杆2 向上
                    if (action)
                        code = "U";
                    else
                        code = "V";
                    break;
                case R.id.push_two_down://推杆2 向下
                    if (action)
                        code = "W";
                    else
                        code = "V";
                    break;
                case R.id.turbine_up://涡轮 向上
                    if (action)
                        code = "O";
                    else
                        code = "P";
                    break;
                case R.id.turbine_down://涡轮 向下
                    if (action)
                        code = "Q";
                    else
                        code = "P";
                    break;
                    */
            }}
        if (action){
            myHandler.sendEmptyMessage(2);
        }else{
            myHandler.sendEmptyMessage(3);
        }


    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void sendByBle(String send_et) {
        L.i(TAG, "sendByBle-->" + send_et);
        if (TextUtils.isEmpty(send_et))
            return;
        Log.i("WWDZ",send_et);
        byte[] buff = send_et.getBytes();
        int len = buff.length;
        int[] lens = dataSeparate(len);
        for (int i = 0; i < lens[0]; i++) {
            String str = new String(buff, 20 * i, 20);
            target_chara.setValue(str);//只能一次发送20字节，所以这里要分包发送
            //调用蓝牙服务的写特征值方法实现发送数据
            mBluetoothLeService.writeCharacteristic(target_chara);
        }
        if (lens[1] != 0) {
            String str = new String(buff, 20 * lens[0], lens[1]);
            if (target_chara != null) {
                target_chara.setValue(str);
                //调用蓝牙服务的写特征值方法实现发送数据
                mBluetoothLeService.writeCharacteristic(target_chara);
            } else {
                Toast.makeText(this, "蓝牙特征为空", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 将数据分包
     **/
    public int[] dataSeparate(int len) {
        int[] lens = new int[2];
        lens[0] = len / 20;
        lens[1] = len - 20 * lens[0];
        return lens;
    }


    @Override
    public void onNavAndSpeed(int nav) {
        if(mNav != nav){
            isTouch = false;
            myHandler.removeMessages(2);
        }
        if (!isTouch) {

            isTouch = true;
            mNav = nav;
            if (nav == 5) {
                code = "6";//右
                myHandler.sendEmptyMessage(2);
            } else if (nav == 3) {
                code = "8";//下
                myHandler.sendEmptyMessage(2);
            } else if (nav == 7) {
                code = "2";//上
                myHandler.sendEmptyMessage(2);
            } else if (nav == 1) {
                code = "4";//左
                myHandler.sendEmptyMessage(2);
            } else {
                code = "5";//停
                myHandler.sendEmptyMessage(3);
            }
//        if (!TextUtils.isEmpty(code))
//            sendByBle(code);
        }
    }

    @Override
    public void onTouchDown() {
        isTouch = false;
        myHandler.removeMessages(2);
        sendByBle("5");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.e("www", "onDestroy");
        //解除广播接收器
        unregisterReceiver(mGattUpdateReceiver);
        unbindService(mServiceConnection) ;
        mBluetoothLeService = null;

    }
}